import models.MyConfig;
import models.ReadProperties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created by yangxianming on 2018/12/14.
 *
 */
@WebServlet(name = "operate", urlPatterns = {"/operate/*"}, loadOnStartup = 2)
public class Operate extends HttpServlet {
    MyConfig myConfig;

    public void init(ServletConfig config) throws ServletException {
        //初始的时候返回这个java的对象，如果出现2个
        myConfig = new MyConfig();
        myConfig.setJavaPidList(get_current_java_pid());
        ReadProperties readProperties = new ReadProperties(config.getServletContext().getRealPath("/"));
        myConfig.setPropertiesConfig(readProperties);
        myConfig.setAppPath(config.getServletContext().getRealPath("/"));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //start
        long start = new Date().getTime();
        String returnString = "";

        response.setHeader("Content-type", "text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        //首字母大写
        char[] cs = request.getPathInfo().substring(1).toCharArray();
        cs[0] -= 32;

        Class<?> action;
        try {
            action = Class.forName("operateBusiness." + String.valueOf(cs));
            Method method = action.getDeclaredMethod("doIt", HttpServletRequest.class, MyConfig.class);
            returnString = (String)method.invoke(action.newInstance(), request, myConfig);
        }catch (Exception e){
            e.printStackTrace();
        }

        //end
        long end = new Date().getTime();
        System.out.println(request.getRequestURI() + "; run time: " + (end-start) + "ms");

        out.print(returnString);
    }

    @Override
    public void destroy()
    {
    }

    private ArrayList<String> get_current_java_pid(){
        // win命令 tasklist /FI "IMAGENAME eq java*"
        ArrayList<String> javaPidList = new ArrayList<String>();
        try {
            Process process = Runtime.getRuntime().exec("tasklist /FI \"IMAGENAME eq java*\"");
            Reader reader = new InputStreamReader(process.getInputStream(), Charset.forName("GBK"));
            BufferedReader bf = new BufferedReader(reader);
            String line;
            while ((line = bf.readLine()) != null){
                System.out.println("tasklist line:" + line);
                if (line.contains("java")){
                    String[] oneList = line.split("\\s+");
                    System.out.println(oneList);
                    javaPidList.add(oneList[1]);
                }
            }
            System.out.println("java pid list: " + javaPidList.toString());
            if (javaPidList.size() > 1){
                System.out.println("java pid 超过了1个，建议先关闭其他java进程后在重启服务器");
                System.out.println("win系统下pid命令 taskkill /F /pid xxx");
            }
            return javaPidList;
        }catch (Exception e){
            e.printStackTrace();
            return javaPidList;
        }
    }
}
